package com.example.mybaseapp.ui

import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.mybaseapp.R
import com.example.mybaseapp.util.LiveDataBus
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class LiveDataActivity : AppCompatActivity() {
    private lateinit var tx:TextView
    private var content = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_live_data)
        initView()
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun initView() {
        tx = findViewById(R.id.tx)
        MainScope().launch(Main){
            LiveDataBus.with<Int>(LiveDataBus.Fu_Coin_Change).observe(this@LiveDataActivity){
                if(it!=0) {
                    LiveDataBus.with<Int>(LiveDataBus.Fu_Coin_Change).value = 0
                    Log.d("LiveDataActivity", "initView: $it")
                    content += "$it\n"
                    tx.text = content
                }
            }
            LiveDataBus.apply {
                with<Int>(Fu_Coin_Change).setValue(1)
            }
//            delay(50)
            LiveDataBus.apply {
                with<Int>(Fu_Coin_Change).setValue(1)
            }
//            delay(50)
            LiveDataBus.apply {
                with<Int>(Fu_Coin_Change).setValue(1)
            }
//            delay(50)
            LiveDataBus.apply {
                with<Int>(Fu_Coin_Change).setValue(1)
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
    }
}